<template>
  <div class="regional-pricing-tab">
    <el-row type="flex" justify="end">
      <el-button type="primary" icon="el-icon-plus" @click="handleClickAdd" class="mb_20">{{ $t('common.base.newRegionalPricing') }}</el-button>
    </el-row>

    <RegionalPricingTabTable ref="regionalRricingTabTable" :columnFields="getColumns" :columnData="dataList" :totalNumber="total" :queryParams="queryParams" @handleCurrentChange="handleCurrentChange" @handleClickEdit="handleClickEdit" @handleClickDelete="handleClickDelete" @handleSubmitPriorityDialog="handleSubmitPriorityDialog"></RegionalPricingTabTable>

    <!-- 新建区域定价弹框 -->
    <base-modal :show.sync="showDialog" :title="titleText" width="600px" @close="handleClose">
      <el-form ref="formRef" :model="ruleForm" :rules="rules" label-position="top">
        <el-form-item :label="$t('common.base.condition')" prop="areaCondition" class="mb_20">
          <el-select v-model="ruleForm.areaCondition" :placeholder="$t('task.tip.allotRuleTip5')">
            <el-option v-for="item in conditionOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('common.base.locationMap.area')" prop="regions">
          <base-dist-picker-international-multi ref="baseDistPickerInternational" @input="handleCitySelectorChange" v-model="ruleForm.regions" />
        </el-form-item>

        <el-form-item :label="$t('servicePrice.list.displayName.salePrice')" prop="unitPrice">
          <el-row type="flex" justify="space-between" :gutter="10">
            <el-col :span="16">
              <el-input v-model.number="ruleForm.unitPrice" @input="filterNumber($event)"></el-input>
            </el-col>
            <el-col :span="8">
              <el-select v-model="ruleForm.currencyType">
                <el-option v-for="item in currencyOption" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="handleClose">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmit" :disabled="dialogPending">{{ $t('common.base.confirm') }}</el-button>
      </div>
    </base-modal>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, ref, onMounted } from 'vue';
import i18n from '@src/locales';
import { MessageBox } from 'element-ui';
import { toast } from '@src/util/platform';
import { currencyOption } from '@src/util/currency';
import { getColumns, conditionOption } from '@src/modules/servicePrice/components/RegionalPricingTab/fields.js';

import RegionalPricingTabTable from '@src/modules/servicePrice/components/RegionalPricingTab/RegionalPricingTabTable.vue';

import { getAreaPriceList, getAreaPriceSave, getAreaPriceDelete, getAreaPricePrimary } from '@src/api/ServicePriceApi';

export default defineComponent({
  name: 'regional-pricing-tab',
  components: {
    RegionalPricingTabTable,
  },
  props: {
    serviceId: {
      type: String | Number,
      default: '',
    },
    servicePrice: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props, { emit }) {
    const formRef = ref();
    const regionalRricingTabTable = ref();

    const checkSalePrice = (rule, value, callback) => {
      const val = Number(value);
      if (value === '') {
        callback(new Error(i18n.t('servicePrice.edit.tip7')));
      } else if (val < 0 || isNaN(val)) {
        callback(new Error(i18n.t('servicePrice.edit.tip8')));
      } else if (val > 999999999){
        callback(new Error(i18n.t('common.base.salePriceTip'))); 
      } else {
        callback();
      }
    };

    const state = reactive({
      ruleForm: {
        id: '',
        areaCondition: 'INCLUDE',
        regions: [],
        unitPrice: '',
        currencyType: 'CNY',
      },
      dataList: [],
      total: 0,
      showDialog: false,
      titleText: i18n.t('common.base.newRegionalPricing'),
      form: {},
      rules: {
        areaCondition: [{ required: true, message: i18n.t('task.tip.allotRuleTip5'), trigger: 'change' }],
        regions: [{ required: true, message: i18n.t('common.placeholder.selectArea'), trigger: 'change' }],
        unitPrice: [{ required: true, validator: checkSalePrice, trigger: 'blur' }],
      },
      queryParams: {
        listLoading: false,
        pageSize: 10,
        pageNum: 1,
      },
      dialogPending: false,
    });

    // 获取区域定价列表
    const fetchRegionalPricingList = async () => {
      state.queryParams.listLoading = true;
      try {
        let ret = await getAreaPriceList({
          relationId: props.serviceId,
          relationType: 'SERVICE_PRICE',
          pageNum: state.queryParams.pageNum,
          pageSize: state.queryParams.pageSize,
        });
        const { success, message, result } = ret || {};

        if (!success) return toast(message, 'error');
        state.dataList = result.list;
        state.total = result.total;
      } catch (err) {
        console.log('error => fetchRegionalPricingList', err);
      } finally {
        state.queryParams.listLoading = false;
      }
    };

    // 切换分页
    const handleCurrentChange = pN => {
      state.queryParams.pageNum = pN;
      fetchRegionalPricingList();
    };

    // 新增
    const handleClickAdd = () => {
      state.showDialog = true;
      state.titleText = i18n.t('common.base.newRegionalPricing');

      state.ruleForm.unitPrice = props.servicePrice?.salePrice || '';
      state.ruleForm.currencyType = props.servicePrice?.salePriceCurrency || 'CNY';
    };

    const areaParams = val => {
      const result = Object.values(val).map(item => [item.adCountry, item.adProvince, item.adCity, item.adDist].filter(Boolean));
      return result;
    };

    // 编辑
    const handleClickEdit = row => {
      state.ruleForm = {
        ...row,
        regions: areaParams(row.regions),
      };
      state.showDialog = true;
      state.titleText = i18n.t('common.base.editRegionalPricing');
    };

    // 点击删除
    const handleClickDelete = ({ id }) => {
      MessageBox.confirm(i18n.t('product.deleteTips'), i18n.t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            getAreaPriceDelete({ id }).then(res => {
              instance.confirmButtonLoading = false;
              if (!res.success) {
                return toast(res.message, 'error');
              }
              toast(i18n.t('common.base.tip.deleteSuccess'), 'success');
              done();
              state.queryParams.pageNum = 1;
              fetchRegionalPricingList();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    };

    const handleClose = () => {
      if (!formRef.value) return;
      formRef.value.resetFields();
      state.ruleForm.currencyType = 'CNY';
      state.ruleForm.id = '';
      state.showDialog = false;
    };

    // 保存区域定价
    const handleSubmit = async () => {
      if (!formRef.value) return;

      const ret = (state.ruleForm.regions || []).map(item => {
        return {
          adCountry: item[0],
          adProvince: item[1] || '',
          adCity: item[2] || '',
          adDist: item[3] || '',
        };
      });

      const params = {
        relationId: props.serviceId,
        relationType: 'SERVICE_PRICE',
        ...state.ruleForm,
        regions: ret,
      };

      await formRef.value.validate((valid, fields) => {
        if (valid) {
          state.dialogPending = true
          getAreaPriceSave(params).then(res => {
            state.dialogPending = false
            const { success, message } = res || {};
            if (!success) toast(message, 'error');

            handleClose();
            fetchRegionalPricingList();
          }).catch(err => {
            state.dialogPending = false
          });
        } else {
          console.log('error submit!', fields);
        }
      });
    };

    // change 区域
    const handleCitySelectorChange = val => {
      state.ruleForm.regions = val;
    };

    // 调整优先级
    const handleSubmitPriorityDialog = ({ id, orderId }, newValue) => {
      try {
        getAreaPricePrimary({
          id,
          oldOrderId: orderId,
          newOrderId: newValue,
        }).then(res => {
          const { success, message } = res || {};

          if (!success) return toast(message, 'error');

          state.queryParams.pageNum = 1;
          fetchRegionalPricingList();
          regionalRricingTabTable.value && regionalRricingTabTable.value.handleClosePriorityDialog();
        });
      } catch (err) {
        console.log('error => handleSubmitPriorityDialog', err);
      }
    };

    const filterNumber = value => {
      if (!value) return;
      let reg = /^[0-9]+([.]{1}[0-9]{0,2}){0,1}$/;
      let num = reg.test(value) ? value : isNaN(Number(value)) ? '' : Number(value).toFixed(3).slice(0, -1);
      state.ruleForm.unitPrice = num;
    };

    onMounted(() => {
      fetchRegionalPricingList();
    });

    return {
      formRef,
      regionalRricingTabTable,
      ...toRefs(state),
      getColumns,
      handleClickAdd,
      handleCurrentChange,
      handleClickEdit,
      handleClickDelete,
      handleClose,
      handleSubmit,
      handleCitySelectorChange,
      conditionOption,
      handleSubmitPriorityDialog,
      filterNumber,
      currencyOption,
    };
  },
});
</script>
<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 20px !important;
}
</style>
